package com.ias.agdis_r.service;

import android.annotation.SuppressLint;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.IBinder;
import android.util.Log;

import com.ias.agdis_r.R;
import com.ias.agdis_r.manager.DataBaseManager;
import com.ias.agdis_r.manager.EffectManager;
import com.ias.agdis_r.module.ParameterModel;
import com.ias.agdis_r.util.S;
import com.ias.agdis_r.util.sdcard.WriteLog;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

@SuppressLint("DefaultLocale")
public class CheckNetService extends Service {

	private static int CHECK_NET_TIME = 2 * 1000;
	private String PUBLIC_STATUS = "CLOSE";
	private String PRIVATE_STATUS = "CLOSE";
	private String WIFI_STATUS = "CLOSE";
	private boolean SEND_STATUS_CHECK = true;
	public String PUBLIC_TAB = "PUBLIC_TAB";
	public String WIFI_TAB = "WIFI_TAB";
	public String PRIVATE_TAB = "eth0";// "eth0"; //"wimax0"; //专网路由标志
	public static final String PUBLIC_COOLPAD_TAB = "ccinet";
	Thread checkNetThread = null;
	private Context context = DataBaseManager.getInstance().getContext();

	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void onCreate() {
		super.onCreate();
		WriteLog.getInstance().writeLog("CheckNetService-OnCreate");
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		loadConfing();
		if(checkNetThread==null) {
			checkNetThread = new CheckNetThread();
			checkNetThread.start();
		}

		return super.onStartCommand(intent, flags, startId);
	}

	public void loadConfing() {
		String private_tab = DataBaseManager.getInstance().getString(
				ParameterModel.T_NET_SELECT_INFO, ParameterModel.PRIVATE_TAB);
		if (S.isNotEmpty(private_tab)) {
			PRIVATE_TAB = private_tab;
		}
		WriteLog.getInstance().writeDebugLog(context.getString(R.string.DEBUG_PRIVATE_IFACE) + private_tab);
		SEND_STATUS_CHECK = true;
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
	}

	class CheckNetThread extends Thread {

		@Override
		public void destroy() {
			super.destroy();
		}

		@Override
		public void run() {
			super.run();
			while (true) {
				checkNet();
				try {
					Thread.sleep(CHECK_NET_TIME);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}

	}

	public void checkNet() {

		String wifi_ip = getLocalIpAddress(WIFI_TAB);
		String private_ip = getLocalIpAddress(PRIVATE_TAB);

		WriteLog.getInstance().writeDebugLog(context.getString(R.string.DEBUG_LOCAL_WIFI_IP)+wifi_ip);
		WriteLog.getInstance().writeDebugLog(context.getString(R.string.DEBUG_LOCAL_PRIVATE_IP)+private_ip);

		// 获取WIFI的IP地址
		if (S.isNotEmpty(wifi_ip)) {
			// 如果WIFI上一次的状态不可用
			if (WIFI_STATUS == "CLOSE") {
				EffectManager.getInstance().ttsPlay(
						EffectManager.TTS_TYPE_BASE, context.getString(R.string.wifiEnable), false);
				WIFI_STATUS = "OPEN";
				netStatusBroadcast("WIFI");
			}
			WifiInfo wifiInfo = getWifiInfo();
			if (null != wifiInfo) {
				WriteLog.getInstance().writeDebugLog(context.getString(R.string.wifiRSSI) + wifiInfo.getRssi());
			}
		} else {
			// 如果WIFI上一次的状态可用
			if (WIFI_STATUS == "OPEN") {
				EffectManager.getInstance().ttsPlay(
						EffectManager.TTS_TYPE_BASE, context.getString(R.string.wifiUnable), false);
				WIFI_STATUS = "CLOSE";
				netStatusBroadcast("WIFI");
			}
		}

		// 获取LTE的IP地址
		if (S.isNotEmpty(private_ip)) {
			if (PRIVATE_STATUS == "CLOSE") {
				EffectManager.getInstance().ttsPlay(
						EffectManager.TTS_TYPE_BASE, context.getString(R.string.priEnable), false);
				PRIVATE_STATUS = "OPEN";
				netStatusBroadcast("PRIVATE");
			}
		} else {
			if (PRIVATE_STATUS == "OPEN") {
				EffectManager.getInstance().ttsPlay(
						EffectManager.TTS_TYPE_BASE, context.getString(R.string.priEnable), false);
				PRIVATE_STATUS = "CLOSE";
				netStatusBroadcast("PRIVATE");
			}
		}


		String public_ip = getLocalIpAddress(PUBLIC_TAB);
		WriteLog.getInstance().writeDebugLog(context.getString(R.string.DEBUG_LOCAL_PUBLIC_IP)+ public_ip);
		// 获取公网的IP地址
		if (S.isNotEmpty(public_ip)) {
			if (PUBLIC_STATUS == "CLOSE") {
				EffectManager.getInstance().ttsPlay(
							EffectManager.TTS_TYPE_BASE, context.getString(R.string.pubEnable), false);
				PUBLIC_STATUS = "OPEN";
					netStatusBroadcast("PUBLIC");
				}
		} else {
			if (PUBLIC_STATUS == "OPEN") {
				EffectManager.getInstance().ttsPlay(
						EffectManager.TTS_TYPE_BASE, context.getString(R.string.pubUnable), false);
				PUBLIC_STATUS = "CLOSE";
				netStatusBroadcast("PUBLIC");
			}
		}

		// 调用者启动后发送所有网络状态，只发送一次
//		if (SEND_STATUS_CHECK) {
////			netStatusBroadcast("PUBLIC");
////			netStatusBroadcast("PRIVATE");
//			netStatusBroadcast("WIFI");
//			SEND_STATUS_CHECK = false;
//		}
	}

	/**
	 * 网络状态改变发送广播
	 */
	private void netStatusBroadcast(String tab) {
		Intent intent = new Intent("ias.routeservice.NET_STATUS_RECEIVER");
		if ("PUBLIC".equals(tab)) {
			intent.putExtra("PUBLIC_STATUS", PUBLIC_STATUS);
			intent.putExtra("PUBLIC_IP", getLocalIpAddress(PUBLIC_TAB));
		} else if ("PRIVATE".equals(tab)) {
			intent.putExtra("PRIVATE_STATUS", PRIVATE_STATUS);
			intent.putExtra("PRIVATE_IP", getLocalIpAddress(PRIVATE_TAB));
		} else if ("WIFI".equals(tab)) {
			intent.putExtra("WIFI_STATUS", WIFI_STATUS);
			intent.putExtra("WIFI_IP", getLocalIpAddress(WIFI_TAB));
			WifiInfo info = getWifiInfo();
			if (null != info) {
				intent.putExtra("SSID", info.getSSID());
				intent.putExtra("RSSI", info.getRssi());
			}
		} else {
			return;
		}
		EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_BASE, context.getString(R.string.netChange), false);
		sendBroadcast(intent);
	}

	private WifiInfo getWifiInfo() {
		WifiManager wifiMgr = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
		if (null == wifiMgr) {
			return null;
		}
		return wifiMgr.getConnectionInfo();
	}

	/**
	 * 获取本机IP地址
	 *
	 * @return
	 */
	public String getLocalIpAddress(String iface) {
		String localIp = "";
		if ("WIFI_TAB".equals(iface)) {
			WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
			if (null != wifiManager) {
				WifiInfo wifiInfo = wifiManager.getConnectionInfo();
				int ipAddress = wifiInfo.getIpAddress();
				if (0 != ipAddress) {
					localIp = intToIp(ipAddress);
				}
			}
		} else if ("PUBLIC_TAB".equals(iface)) {
			ConnectivityManager connManager = (ConnectivityManager) getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
			if (null != connManager) {
				NetworkInfo info = connManager.getActiveNetworkInfo();
				if (info != null && info.isConnected()) {
					if (info.getType() == ConnectivityManager.TYPE_MOBILE) {
						try {
							for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
								NetworkInterface intf = en.nextElement();
								for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
									InetAddress inetAddress = enumIpAddr.nextElement();
									if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
										localIp = inetAddress.getHostAddress();
									}
								}
							}
						} catch (SocketException e) {
							e.printStackTrace();
						}
					}
				}
			}
		} else {
			try {
				outter:
				for (Enumeration<NetworkInterface> en = NetworkInterface
						.getNetworkInterfaces(); en.hasMoreElements(); ) {
					NetworkInterface intf = en.nextElement();
					if (intf.getName().toLowerCase().indexOf(iface) > -1) {
						for (Enumeration<InetAddress> enumIpAddr = intf
								.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
							InetAddress inetAddress = enumIpAddr.nextElement();
							if (!inetAddress.isLoopbackAddress()) {
								localIp = inetAddress.getHostAddress().toString();
								if (localIp.contains("::")) {// ipV6的地址
									localIp = "";
								} else {
									break outter;
								}
							}
						}
					}
				}
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}
		// WriteLog.getInstance().writeLog("获取本机"+iface+"IP地址:"+localIp);
		Log.i("tag", "获取本机" + iface + ",IP地址:" + localIp);
		return localIp;
	}

	private String intToIp(int i) {
		return (i & 0xFF) + "." + ((i >> 8) & 0xFF) + "." +
				((i >> 16) & 0xFF) + "." + (i >> 24 & 0xFF);
	}
}

